import { registerEnt } from '@/api/codeServer'
import { Button, Tabs, message, type TabsProps } from 'antd'
import { useRef, useState } from 'react'
import { YmTable, type YmTablePorps } from 'ym-design'
import CarModal from './modal/CarModal'
import { ChoiceCompany } from './modal/ChoiceCompany'
import PersonModal from './modal/PersonModal'
import { useTableConfig } from './useTableConfig'

export type TabKey = '1' | '2' | '3'

interface PropsType {
  associationId?: string
}

export const DetailTable: React.FC<PropsType> = ({ associationId }) => {
  const [key, setKey] = useState<TabKey>('1')
  const onChange = (key: string) => {
    setKey(key as TabKey)
  }
  const [personVisible, setPersonVisible] = useState<boolean>(false)
  const [carVisible, setCarVisible] = useState<boolean>(false)
  const modalRef = useRef<{ showModal: () => void }>(null)
  const [entId, setEntId] = useState<string>()
  const { tableProps, refresh } = useTableConfig({
    tabKey: key,
    modalRef,
    associationId,
    showPersonModal: (entId: string) => {
      setEntId(entId)
      setPersonVisible(true)
    },
    showCarModal: (entId: string) => {
      setEntId(entId)
      setCarVisible(true)
    }
  })

  const items: TabsProps['items'] = [
    {
      key: '1',
      label: '备案企业'
    },
    {
      key: '2',
      label: '备案人员'
    },
    {
      key: '3',
      label: '备案车辆'
    }
  ]

  const handleRegister = (entIds: string) => {
    registerEnt({ associationId: associationId!, entIds }).then(() => {
      message.success({
        content: '操作成功'
      })
      refresh(Math.random())
    })
  }

  return (
    <>
      <Tabs
        defaultActiveKey="1"
        tabBarStyle={{ paddingLeft: 24 }}
        items={items}
        onChange={onChange}
      />
      <div style={{ height: 'calc(100% - 62px)' }}>
        <YmTable {...(tableProps as YmTablePorps)} />
      </div>
      <ChoiceCompany
        innerRef={modalRef}
        onChange={handleRegister}
        associationId={associationId}
      />
      <PersonModal
        entId={entId}
        associationId={associationId}
        open={personVisible}
        onCancel={() => setPersonVisible(false)}
        footer={[
          <Button key="back" onClick={() => setPersonVisible(false)}>
            关闭
          </Button>
        ]}
      />

      <CarModal
        associationId={associationId}
        entId={entId}
        open={carVisible}
        onCancel={() => setCarVisible(false)}
        footer={[
          <Button key="back" onClick={() => setCarVisible(false)}>
            关闭
          </Button>
        ]}
      />
    </>
  )
}
